package bot

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/sirupsen/logrus"
)

type CobotHandler struct {
	cobotStatusCount int
}

func NewCobotHandler() *CobotHandler {
	// 设置logrus的Formatter为textformatter，并开启显示函数名
	return &CobotHandler{}
}

func (cobot *CobotHandler) Sleep() int {
	r := rand.Intn(3) + 2
	time.Sleep(time.Duration(r) * time.Second)
	return r
}

/* 获取机器人的连接状态 */
func (cobot *CobotHandler) GetCobotStatus(w http.ResponseWriter, r *http.Request) {
	logrus.Debug("Entry")
	logrus.Print("GetCobotStatus")
	if r.Method == "GET" || r.Method == "POST" {
		// w.WriteHeader(http.StatusNotFound)
		// w.Write([]byte("oops"))
		// return
		// 读取文件内容
		inputFile := "webserver/assets/bot/cobot/cobot_getCobotStatus.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			// buf, err := os.ReadFile(inputFile)
			inputReader := bufio.NewReader(inputReader)
			// for {
			// 	inputBytes, err := inputReader.ReadBytes('\n') // 循环读取文件内容，每次以 '\n'字符为一次读取的终止
			// 	inputString := string(inputBytes)
			// 	fmt.Printf("== inputString: %v\n", inputString)
			// 	if err == io.EOF { // 文件结束
			// 		return
			// 	}
			// }
			// inputReader = bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			// io.WriteString()
			io.Copy(w, inputReader)
		}
	}
}

/*
连接
*/
func (cobot *CobotHandler) Connect(w http.ResponseWriter, r *http.Request) {
	logrus.Debug("Entry")
	t := cobot.Sleep()
	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()
		ip := r.Form.Get("ip")

		var response = make(map[string]interface{})
		var body = make(map[string]interface{})
		if len(ip) > 0 {
			response["code"] = 200
			response["msg"] = "机械臂未连接sssss"
			body["data"] = true
			body["msg"] = "机械臂未连接sss"
			response["body"] = body
		} else {
			response["code"] = 400
			response["msg"] = "failure"
			body["data"] = true
			body["msg"] = ""
			response["body"] = body
		}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	case "POST":
		ip := r.FormValue("ip")

		var response = make(map[string]interface{})
		if len(ip) > 0 {
			response["code"] = 200
			response["msg"] = "机械臂未连接"
			response["data"] = map[string]string{"msg": "connect success", "rand": strconv.Itoa(t), "status": "0"}
		} else {
			response["code"] = -1
			response["msg"] = "failure"
			response["data"] = map[string]string{"msg": "The IP cannot be empty", "rand": strconv.Itoa(t), "status": "-1"}
		}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	}
}

/*
断开连接
*/
func (cobot *CobotHandler) Disconnect(w http.ResponseWriter, r *http.Request) {
	logrus.Debug("Entry")
	t := cobot.Sleep()
	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})
		var body = make(map[string]interface{})

		response["code"] = 200
		response["msg"] = "success"
		body["data"] = map[string]string{"uid": "Xsssdsdsd", "rand": strconv.Itoa(t), "status": "0"}
		body["msg"] = "disconnect success"
		response["body"] = body

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	case "POST":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})

		response["code"] = 200
		response["msg"] = "success"
		response["data"] = map[string]string{"msg": "disconnect success", "uid": "Xsssdsdsd", "rand": strconv.Itoa(t), "status": "0"}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	}
}

/*
打开电源
*/
func (cobot *CobotHandler) PowerOn(w http.ResponseWriter, r *http.Request) {
	logrus.Debug("Entry")
	t := cobot.Sleep()
	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})
		var body = make(map[string]interface{})

		response["code"] = 200
		response["msg"] = "success"
		body["data"] = map[string]string{"rand": strconv.Itoa(t), "status": "0"}
		body["msg"] = ""
		response["body"] = body

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	case "POST":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})

		response["code"] = 200
		response["msg"] = "success"
		response["data"] = map[string]string{"msg": "", "rand": strconv.Itoa(t), "status": "0"}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	}
}

/*
关闭电源
*/
func (cobot *CobotHandler) PowerOff(w http.ResponseWriter, r *http.Request) {
	logrus.Debug("Entry")
	t := cobot.Sleep()
	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})
		var body = make(map[string]interface{})
		response["code"] = 200
		response["msg"] = "success"
		body["data"] = map[string]string{"uid": "Xsssdsdsd", "rand": strconv.Itoa(t), "status": "0"}
		body["msg"] = ""
		response["body"] = body

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	case "POST":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})
		response["code"] = 200
		response["msg"] = "success"
		response["data"] = map[string]string{"msg": "", "uid": "Xsssdsdsd", "rand": strconv.Itoa(t), "status": "0"}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	}
}

/*
使能机器人
*/
func (cobot *CobotHandler) EnableRobot(w http.ResponseWriter, r *http.Request) {
	logrus.Debug("Entry")
	t := cobot.Sleep()
	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})
		var body = make(map[string]interface{})
		response["code"] = 200
		response["msg"] = "success"
		body["data"] = map[string]string{"uid": "Xsssdsdsd", "rand": strconv.Itoa(t), "status": "0"}
		body["msg"] = ""
		response["body"] = body

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	case "POST":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})
		response["code"] = 200
		response["msg"] = "success"
		response["data"] = map[string]string{"msg": "", "uid": "Xsssdsdsd", "rand": strconv.Itoa(t), "status": "0"}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)

	}
}

/*
机器人下使能
*/
func (cobot *CobotHandler) DisableRobot(w http.ResponseWriter, r *http.Request) {
	logrus.Debug("Entry")
	t := cobot.Sleep()
	switch r.Method {
	case "GET":

		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})
		var body = make(map[string]interface{})
		response["code"] = 200
		response["msg"] = "success"
		body["data"] = map[string]string{"status": "0", "rand": string(t)}
		body["msg"] = ""
		response["body"] = body

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	case "POST":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()

		var response = make(map[string]interface{})
		response["code"] = 200
		response["msg"] = "success"
		response["data"] = map[string]string{"msg": "", "status": "0", "rand": string(t)}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	}
}

/*
复位
*/
func (cobot *CobotHandler) ResetAlarm(w http.ResponseWriter, r *http.Request) {
	logrus.Debug("Entry")
	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/json")
		// 写入 sessionid 的方式代替 token
		r.ParseForm()
		var response = make(map[string]interface{})

		response["code"] = 200
		response["msg"] = "success"
		response["body"] = map[string]string{"result": "1", "msg": "Reset success"}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	}
}

func (cobot *CobotHandler) RunWeldingProgram(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		inputFile := "webserver/assets/bot/cobot/cobot_runWeldingProgram.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
}

func (cobot *CobotHandler) SuspendWeldingProgram(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		inputFile := "webserver/assets/bot/cobot/cobot_suspendWeldingProgram.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
}

func (cobot *CobotHandler) ContinueWeldingProgram(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		inputFile := "webserver/assets/bot/cobot/cobot_continueWeldingProgram.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
}

func (cobot *CobotHandler) StopWeldingProgram(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		inputFile := "webserver/assets/bot/cobot/cobot_stopWeldingProgram.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
}

func (cobot *CobotHandler) SetCobotRapidRate(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		inputFile := "webserver/assets/bot/cobot/cobot_setCobotRapidRate.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
}

func (cobot *CobotHandler) GetTeachingPoint(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		inputFile := "webserver/assets/bot/cobot/cobot_getTeachingPoint.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
}
